package com.leetcode.algorithm.y22.m07.w4;

import java.util.PriorityQueue;

/**
 * 215. 数组中的第K个最大元素
 * 
 * https://leetcode.cn/problems/kth-largest-element-in-an-array/
 * 
 * @author jie.deng
 *
 */
class Question0215Solution01 {

	public int findKthLargest(int[] nums, int k) {
		int len = nums.length;
		if (k <= len / 2) {
			PriorityQueue<Integer> queue = new PriorityQueue<>((i1, i2) -> i2 - i1);
			for (int num : nums) {
				queue.offer(num);
			}
			int idx = 1;
			while (idx < k) {
				queue.poll();
				idx++;
			}
			return queue.poll().intValue();
		} else {
			return findKthSmallest(nums, len - k + 1);
		}
	}

	private int findKthSmallest(int[] nums, int k) {
		PriorityQueue<Integer> queue = new PriorityQueue<>();
		for (int num : nums) {
			queue.offer(num);
		}
		int idx = 1;
		while (idx < k) {
			queue.poll();
			idx++;
		}
		return queue.poll().intValue();
	}

}